package com.ptswitch.material.pages.user;

import java.util.List;

import org.apache.tapestry5.EventConstants;
import org.apache.tapestry5.annotations.InjectPage;
import org.apache.tapestry5.annotations.OnEvent;
import org.apache.tapestry5.annotations.Property;
import org.apache.tapestry5.ioc.annotations.Inject;
import org.hxzon.tapestry5.model.ValueGrouper;
import org.hxzon.tapestry5.model.ValueLabel;
import org.slf4j.Logger;

import com.ptswitch.material.model.security.Permission;
import com.ptswitch.material.model.security.Role;
import com.ptswitch.material.pages.base.PageBase;
import com.ptswitch.material.service.PermissionService;
import com.ptswitch.material.service.RoleService;
import com.ptswitch.material.util.ValueLabelUtil;
import com.ptswitch.material.util.security.PermissionUtil;
import com.ptswitch.material.util.security.RoleEditUtil;
import com.ptswitch.material.util.security.RoleUtil;

public class EditPermission extends PageBase {
    @Inject
    private Logger logger;
    @Inject
    private RoleService roleSer;
    @Inject
    private PermissionService permissionSer;
    @InjectPage
    private ListRole listRole;
    //
    @Property
    private Permission permission;
    @Property
    private List<Role> permissionRoles;
    @Property
    private List<Role> roles;
    @Property
    private ValueLabel<Role> roleLabel = ValueLabelUtil.roleLabel;
    @Property
    private ValueGrouper<Role> roleGrouper = RoleUtil.roleValueGrouper;

    @OnEvent(value = EventConstants.ACTIVATE)
    Object init(long id) {
        checkPermitted(PermissionUtil.PermissionEdit);
        //init for display or update
        permission = permissionSer.findByIdWithRoles(id);
        permissionRoles = RoleEditUtil.getRoles(permission);
        roles = roleSer.findAll();
        return null;
    }

    @OnEvent(value = EventConstants.PASSIVATE)
    Object onPassivate() {
        return permission.getId();
    }

    @OnEvent(value = EventConstants.SUCCESS, component = "update")
    Object update() {
        checkPermitted(PermissionUtil.PermissionEdit);
        permissionSer.save(permission);
        roleSer.saveRolePermissions(RoleEditUtil.toNewRolePermissions(permissionRoles, //
                RoleEditUtil.getRoles(permission), permission));
        //hlog(HlogConstants.updateRole, role);
        return listRole;
    }

}
